<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :showbefore="true">

<!--        使用插槽可以用slot="before"，也可以用下面这种，下面这种必须再template内使用-->
        <template v-slot:before>
<!--左侧显示总记录数-->
          <span>共166条记录</span>
        </template>

        <template v-slot:after>
<!--右侧显示按钮，excel导出-->
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportData">excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmployee">新增员工</el-button>
        </template>
      </PageTools>

      <el-card>
        <el-table border  :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center" width="120px">
            <template v-slot="{ row }">
              <img :src="row.staffPhoto" alt=""
                   v-imgerror="require('@/assets/common/bigUserHeader.png')"
                   @click="showQrCode(row.staffPhoto)"
                   style="border-radius: 50%; width: 100px; height: 100px; padding: 10px" >
            </template>

          </el-table-column>

          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" >
            <template v-slot="{row }" >
              {{row.timeOfEntry | formatDate  }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState" >
            <template v-slot="{ row}">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>

            </template>

          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmploy(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
            layout="total, prev, pager, next" />
        </el-row>

      </el-card>
    </div>
    <add-employee :showdialog.sync="showdialog" @addpeople="addpeople"></add-employee>
    <el-dialog title="二维码"
               :visible.sync="showCode"
               @opened="showQrCode"
               @close="imgUrl=''">

      <el-row  type="flex" justify="center">
      <canvas ref="myCanvas"></canvas>

      </el-row>

    </el-dialog>

  </div>
</template>

<script>
import {getEmployeeList,delEmployee} from "@/api/employees";
import EmployeeEnum from '@/api/constant/employees'  //格式化数据的枚举
import AddEmployee from './components/add-employee'
import {formatDate} from '@/filters'
import QrCode from 'qrcode'



export default {
  components:{
    AddEmployee

  },
data(){

  return{
    list: [], // 接数据的
    page: {
      page: 1, // 当前页码
      size: 10,
      total: 0 // 总数
    },
    showdialog:false, //显示弹窗
    showCode:false //显示二维码弹窗
  }
},
  created() {
  this.getEmployeeList()
  },
  methods:{
    //获取员工的综合信息
    async getEmployeeList(){
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows

    },
  //分页触发的函数
    changePage(newPage){

      this.page.page = newPage
      this.getEmployeeList()

    },
    //格式化聘用形式
    formatEmployment(row, column, cellValue, index){

    const resoult=  EmployeeEnum.hireType.find(item => item.id===cellValue)
      return resoult ? resoult.value : '未知'
    },
//删除员工数据
    async deleteEmploy(id){
      try {
        await this.$confirm('确实删除员工吗','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delEmployee(id)
        this.getEmployeeList()  //更新数据
        this.$message.success('删除员工成功')

      }catch (error){
        console.log(error)
      }

    },

    //新增员工
    addEmployee(){
      this.showdialog=true

    },
    addpeople(){
      this.getEmployeeList()
    },

    exportData(){

      // 表头对应关系
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      //懒加载，点击了再去导入，因为这个插件比较大
      import('@/vendor/Export2Excel').then(async excel=>{
        //因为我现在获取员工的数据是通过页码跟每页显示条数来获取的，所以导出所有数据要重新获取
          const { rows }= await getEmployeeList({page:1,size: this.page.total})
        //根据导出插件中的export_json_to_excel方法的规范，我们需要对数据进行处理
        const data = this.formatJson(headers,rows)

        excel.export_json_to_excel({
          header:Object.keys(headers),
          data:data,
          filename:"员工工资表",
        })

      })
    },


    formatJson(header,rows){
     return  rows.map(item=>{

        return   Object.keys(header).map(key=>{

          if (header[key] === 'timeOfEntry' || header[key] === 'correctionTime') {
            return formatDate(item[header[key]]) // 返回格式化之前的时间
          } else if (header[key] === 'formOfEmployment') {
            var en = EmployeeEnum.hireType.find(obj => obj.id === item[header[key]])
            return en ? en.value : '未知'
          }
          return item[header[key]]
        })


      })},


    showQrCode(url){

      if (url){

        this.showCode=true
        // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后

        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })

      }else {

        this.$message.warning('该用户还未上传头像')
      }

    }



  }


}
</script>

<style>

</style>
